// cart.js
var app = getApp()
var mycart = require('../../utils/mycart.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        status: '0',
        storeId: '',
        storeType: '',
        categories: [],
        listdata: [],
        totalPrice: 0,

        shoppingCart: {
            allPrice: 0,
            count: 0,
            list: []
        },
        showModalStatus: false,

        // 分页字段
        page_offset: 0,
        page_size: 10,
        is_load_all: false,
        //加菜参数
        seat_id: '',
        // 点餐提示语
        toastTitle: '确认要提交吗？'
    },
    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
        }
        return {
            title: '人人点餐',
            path: '/pages/cart/cart?id=' + this.data.storeId + '&storeType=' + this.data.storeType,
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let storeStype = decodeURIComponent(options['storeType'])
        if (options['merchant_id'] && options['seat_id'] && options['storeType']) {
            this.setData({
                storeId: options['merchant_id'],
                seat_id: options['seat_id'],
                storeType: storeStype
            })
        }
        console.log(this.data.storeId + " " + this.data.seat_id)
        console.log(options['id'] + ' ' + storeStype)
        if (options['id'] && options['storeType']) {

            this.setData({
                storeId: options.id,
                storeType: storeStype
            })
        }
        this.initMenuList()   // 初始化菜单列表
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },


    changeMenu: function (e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            status: index,
            currentPosition: "order" + index
        })
    },
    /**
     * 添加商品进入购物车事件
     */
    addEvent: function (event) {
        this.setData({
            shoppingCart: mycart.addEvent(event.currentTarget.dataset.index, this.data.shoppingCart)
        })
    },
    /**
     * 从购物车删除商品事件
     */
    minusEvent: function (event) {
        this.setData({
            shoppingCart: mycart.minusEvent(event.currentTarget.dataset.index, this.data.shoppingCart)
        })
    },
    /**
     * 判断用户是否已经点餐
     */
    isOrder: function (e) {
        var that = this
        switch (this.data.storeType) {
            case "点餐":
            case "加菜":
                that.setData({
                    toastTitle: "确认要添加吗？"
                })
                break;
            case "外卖":
                that.setData({
                    toastTitle: "确认要提交吗？"
                })
                break;
        }
        var num = 0;
        for (var i = 0; i < this.data.shoppingCart.list.length; i++) {
            num += this.data.shoppingCart.list[i].num
        }
        console.log(num)
        if (num > 0) {
            this.powerDrawer(e.currentTarget.dataset.statu)
        }
        else {
            wx.showModal({
                title: '提示',
                content: '您还没有点餐',
                showCancel: false
            })
        }
    },
    /**
     * 提交订单
     */
    submit: function () {
        this.powerDrawer('close')
        var that = this
        console.log(this.data.storeType)

        switch (this.data.storeType) {
            case '点餐':
                app.changeShoppingCart(that.data.storeId, '点餐', that.data.shoppingCart)
                var parm = that.data.shoppingCart
                wx.setStorageSync('shoppingCart', JSON.stringify(parm))
                wx.navigateTo({
                    url: '../save-order/save-order?storeId=' + this.data.storeId + '&storeType=' + this.data.storeType
                })

                break;
            case '外卖':
                app.changeShoppingCart(that.data.storeId, '外卖', that.data.shoppingCart)
                var parm = that.data.shoppingCart
                wx.setStorageSync('shoppingCart', JSON.stringify(parm))
                wx.navigateTo({
                    url: '../submit-order/submit-order?storeId=' + this.data.storeId  + '&storeType=' + this.data.storeType
                })
                break;
            case '加菜':
                app.changeShoppingCart(that.data.storeId, '加菜', that.data.shoppingCart)
                var product = ''
                for (var i = 0; i < that.data.shoppingCart.list.length; i++) {
                    if (that.data.shoppingCart.list[i].num > 0) {
                        product += 'id=' + that.data.shoppingCart.list[i].data.id + '&qty=' + that.data.shoppingCart.list[i].num + ','
                    }
                }
                console.log(that.data.shoppingCart)

                getApp().http.request({
                    url: "/api/v1/menu/save?merchant_id=" + that.data.storeId + "&seat_id=" + that.data.seat_id + "&product=" + encodeURIComponent(product),
                    method: 'POST',
                    data: {},
                    success: function (res) {
                        setTimeout(function () {
                            wx.showToast({
                                title: '快去下单吧',
                                icon: '',
                                image: '',
                                duration: 2000,
                                mask: true,
                                success: function (res) {
                                },
                                complete: function (res) {
                                }
                            })
                        }, 1000),
                            wx.navigateBack({
                                delta: 1
                            })
                        var userShoppingCart = getApp().globalData.shoppingCart
                        //订单保存成功后清理购物车
                        for (var i = 0; i < userShoppingCart.length; i++) {
                            if (that.data.storeId == userShoppingCart[i].mid) {
                                getApp().cleanShoppingCart(that.data.storeId, '外卖')
                            }
                        }
                    },
                    fail: function () {
                        wx.showToast({
                            title: '加菜失败',
                            icon: '',
                            image: '',
                            duration: 2000,
                            mask: true
                        })
                    },
                    complete: function (res) {
                    }
                })
                break;
            default:
                break;
        }
        that.powerDrawer()
    },


    /**
     * 自定义模态窗口相关函数
     */
    powerDrawer: function (parm) {
        var currentStatu = parm;
        this.util(currentStatu)
    },
    util: function (currentStatu) {
        /* 动画部分 */
        // 第1步：创建动画实例
        var animation = wx.createAnimation({
            duration: 200, //动画时长
            timingFunction: "linear", //线性
            delay: 0 //0则不延迟
        });

        // 第2步：这个动画实例赋给当前的动画实例
        this.animation = animation;

        // 第3步：执行第一组动画
        animation.opacity(0).rotateX(-100).step();

        // 第4步：导出动画对象赋给数据对象储存
        this.setData({
            animationData: animation.export()
        })

        // 第5步：设置定时器到指定时候后，执行第二组动画
        setTimeout(function () {
            // 执行第二组动画
            animation.opacity(1).rotateX(0).step();
            // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
            this.setData({
                animationData: animation
            })

            //关闭
            if (currentStatu == "close") {
                this.setData(
                    {
                        showModalStatus: false
                    }
                );
            }
        }.bind(this), 200)

        // 显示
        if (currentStatu == "open") {
            this.setData(
                {
                    showModalStatus: true
                }
            );
        }
    },

    /**
     * 初始化菜单列表
     */
    initMenuList: function () {
        var that = this
        var path = '/api/v1/product?categories_id=&id=' + this.data.storeId + '&offset=' + this.data.page_offset * this.data.page_size;
        getApp().http.request({
            url: path, //仅为示例，并非真实的接口地址
            method: 'GET',
            data: {},
            dataType: 'json',
            success: function (res) {
                console.log(res)
                if (res.data.code == '200') {
                    that.setData({
                        categories: res.data.data.categories
                    })
                    var tmp_shoppingCart = []
                    for (var i = 0; i < res.data.data.list.length; i++) {
                        tmp_shoppingCart.push({'num': 0, 'data': res.data.data.list[i]})
                    }
                    that.setData({
                        shoppingCart: {
                            allPrice: 0,
                            count: 0,
                            list: tmp_shoppingCart
                        }
                    })
                }
                // 判断购物车是否为空
                if (app.globalData.shoppingCart.length > 0) {
                    console.log(app.globalData.shoppingCart)
                    for (var i = 0; i < app.globalData.shoppingCart.length; i++) {
                        if (app.globalData.shoppingCart[i].mid == that.data.storeId) {
                            var tmp_shoppingCart = {
                                allPrice: 0,
                                count: 0,
                                list: []
                            }
                            switch (that.data.storeType) {
                                case '点餐':
                                    tmp_shoppingCart = app.globalData.shoppingCart[i].data.inShoppingCart
                                    break;
                                case '外卖':
                                    tmp_shoppingCart = app.globalData.shoppingCart[i].data.outShoppingCart
                                    break;
                                case '加菜':
                                    tmp_shoppingCart = {}
                                    break;
                                default:
                                    break;
                            }
                            console.log(JSON.stringify(tmp_shoppingCart) == '{}')
                            if (JSON.stringify(tmp_shoppingCart) != '{}') {
                                console.log('yes')
                                that.setData({
                                    shoppingCart: tmp_shoppingCart
                                })
                            }
                        }
                    }
                }
            },
            fail: function () {
            }
        })
    },

    bindscrolltolower: function () {
        var offset = this.data.page_offset
        offset++
        this.setData({
            page_offset: offset
        })
        console.log(offset)
        var path = '/api/v1/product?categories_id=&id=' + this.data.storeId + '&offset=' + this.data.page_offset * this.data.page_size;
        var that = this
        getApp().http.request({
            url: path, //仅为示例，并非真实的接口地址
            method: 'GET',
            data: {},
            dataType: 'json',
            success: function (res) {
                console.log(res)
                that.setData({
                    categories: res.data.data.categories
                })
                if (res.data.data.list.length > 0) {
                    var tmp_listdata = that.data.listdata

                    var tmp_shoppingCart = []
                    for (var i = 0; i < res.data.data.list.length; i++) {
                        tmp_shoppingCart.push({'num': 0, 'data': res.data.data.list[i]})
                    }
                    that.setData({
                        shoppingCart: {
                            allPrice: 0,
                            count: 0,
                            list: tmp_shoppingCart
                        }
                    })
                } else {
                    if (!that.data.is_load_all) {
                        wx.showToast({
                            title: '没有更多数据了',
                            duration: 2000
                        })
                        that.setData({
                            is_load_all: true
                        })
                    }
                }
            },
            fail: function () {

            }
        })
    },
    drawerScreenEvent: function () {
        this.powerDrawer("close")
    }
})